import os
import statistics
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl
import numpy as np
import pandas as pd

mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42
mpl.rcParams['axes.linewidth'] = 1.5
mpl.rcParams['lines.linewidth'] = 3
mpl.rcParams['lines.markersize'] = 10
mpl.rcParams['font.size'] = 10
mpl.rcParams['font.weight'] = 'bold'
mpl.rcParams['xtick.labelsize'] = 14
mpl.rcParams['ytick.labelsize'] = 14
mpl.rcParams['legend.fontsize'] = 16
mpl.rcParams['legend.framealpha'] = 0
mpl.rcParams['legend.borderpad'] = 0.1
mpl.rcParams["axes.labelweight"] = "bold"
mpl.rcParams["axes.labelsize"] = 18
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['figure.figsize'] = (8, 4)

def plot_vt_cdf1():
    data = {
        'FARM (Fabric-112)': [],
        'FARM (FatTree-40)': [], 
        'B-APKeep (Fabric-112)': [], 
        'B-APKeep (FatTree-40)': []
        }
    for line in open('output/bapkeep.csv', encoding='utf8'):
        if line[0] != ',':
            continue
        arr = line.split(',')
        data['B-APKeep (Fabric-112)'].append(float(arr[5]))
        data['B-APKeep (FatTree-40)'].append(float(arr[4]))

    net_to_dir = {'Fabric-112': 'fb', 'FatTree-40': 'ft40'}
    for method in ['FARM', 'B-APKeep']:
        for net in ['Fabric-112', 'FatTree-40']:
            for dev in ['rsw', 'fsw', 'ssw']:
                devc = {'rsw':40, 'fsw':40, 'ssw':20}
                if net == 'Fabric-112':
                    devc = {'rsw': 89, 'fsw': 7, 'ssw': 4}
                i = devc[dev]
                for line in open('output/%s/inc.%s.txt' % (net_to_dir[net], dev)):
                    if 'time' not in line:
                        continue
                    arr = line.split()
                    data['%s (%s)' % (method, net)].append(float(arr[5])/1000000)
                    i -= 1
                    if i == 0:
                        break
    for d in data:
        data[d] = data[d][:100]
    df = pd.DataFrame(data)
    # plt.figure(figsize=(9,3.5))
    f = sns.ecdfplot(data=df)
    # plt.legend(labels=f.get_legend().get_texts())
    # plt.legend(f.get_legend().get_texts(),fontsize='12')
    sns.move_legend(f, bbox_to_anchor=(0,-0.7), loc="lower left", ncol=2)
    plt.xlabel('Time (ms)', weight='bold')
    plt.ylabel('')
    qt = 0.90
    qtdata = []
    
    for k, v in data.items():
      t = np.array(v)
      qtdata.append((np.quantile(t, qt), qt))
    i = 0
    for e in qtdata:
      plt.vlines(x=e[0], color='black', linestyle=':', ymin=0, ymax=e[1], linewidth=2)
      # plt.hlines(y=e[1], color='black', linestyle=':', xmin=0, xmax=1, linewidth=2)
      if i == 0:
        plt.text(x=e[0], y=e[1], s='(%.3f, %.2f)' % (e[0], e[1]), size=14)
      elif i == 1:
        plt.text(x=e[0], y=e[1]-0.1, s='(%.3f, %.2f)' % (e[0], e[1]), size=14)
      else:
        plt.text(x=e[0]-2, y=e[1]-0.1, s='(%.3f, %.2f)' % (e[0], e[1]), size=14)
      i+=1
    # plt.legend(loc='upper center', bbox_to_anchor=(0.91, 1.), ncol=1)
    # df = pd.DataFrame({'FARM': vts['FARM']})
    # f = sns.ecdfplot(data=df)
    plt.tight_layout(pad=1)
    
    # leg = plt.legend()
    
    # plt.savefig('output/vtcdf-all.pdf')
    plt.show()

def cpu_net_tl(net):
    devs = ['rsw', 'fsw', 'ssw']
    dev_to_standard = {'rsw': 'ToR', 'fsw': 'Agg', 'ssw': 'Core'}
    cpus = {}
    nets = {}
    mems = {}
    for dev in devs:
        cpus[dev] = []
        nets[dev] = []
        mems[dev] = []
        for line in open('output/top.%s.%s.txt' % (net, dev)):
            if line.strip() == '':
                cpus[dev].append(0)
                mems[dev].append(0)
            else:
                arr = line.split()
                cpus[dev].append(float(arr[8])/8)
                mems[dev].append(int(arr[5])/1000)
            # if 'all' in line and 'Average' not in line:
            #     arr = line.split()
            #     cpus[dev].append(float(arr[3]))
        
        
        for line in open('output/fb/sar.net.%s.%s.txt' % (net, dev)):
            if 'Ethernet1 ' in line and 'Average' not in line:
                arr = line.split()
                nets[dev].append(float(arr[6]))
        for i in range(10):
            nets[dev][i] = 0
    print(nets['fsw'])

    x = range(len(cpus['rsw']))
    
    plt.figure()
    markers = ['+', 'x', '.']
    lst = ['m--', '-', '-']
    for dev in devs:
        plt.plot(x, cpus[dev], lst.pop(), marker=markers.pop(), label=dev_to_standard[dev])
    plt.xlabel('Time (s)', weight='bold')
    plt.ylabel('CPU (%)', weight='bold')
    plt.legend()
    plt.ylim(0, 100)
    # plt.grid(False)
    plt.tight_layout(pad=.1)
    plt.savefig('output/fb/cpu.all1.pdf' )

    plt.figure()
    markers = ['+', 'x', '.']
    lst = ['m--', '-', '-']
    for dev in devs:
        plt.plot(x, nets[dev], lst.pop(), marker=markers.pop(), label=dev_to_standard[dev])
    plt.xlabel('Time (s)', weight='bold')
    plt.ylabel('Bandwidth (Kbps)', weight='bold')
    plt.legend()
    # plt.grid(False)
    plt.tight_layout(pad=.1)
    plt.savefig('output/fb/net.all1.pdf')

    plt.figure()
    markers = ['+', 'x', '.']
    lst = ['m--', '-', '-']
    for dev in devs:
        plt.plot(x, mems[dev], lst.pop(), marker=markers.pop(), label=dev_to_standard[dev])
    plt.xlabel('Time (s)', weight='bold')
    plt.ylabel('Memory (MB)', weight='bold')
    plt.legend()
    # plt.grid(False)
    plt.tight_layout(pad=.1)
    plt.savefig('output/fb/mem.all1.pdf')

# plot_vt_cdf1()
cpu_net_tl('fb')